package cn.com.ddapp.ddm.ui.order;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.order.RtListEntity;
import cn.com.ddapp.ddm.enums.OrderEnum;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.dialog.CommonDialog;
import cn.com.ddapp.ddm.ui.dialog.DialogHelper;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.FileUtil;
import cn.com.ddapp.ddm.util.ImageUtils;
import cn.com.ddapp.ddm.util.MethodsCompat;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.StringUtils;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.widget.ImageViewUpLoad;

/**
 * Created by caopenghui on 2016-08-09.
 */
public class AfterSalesActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.rtTypeLinearlay)
    LinearLayout rtTypeLinearlay;//退款类型
    @BindView(R.id.goodsStatusLinearlay)
    LinearLayout goodsStatusLinearlay;//收获状态
    @BindView(R.id.rtReasonLinearlay)
    LinearLayout rtReasonLinearlay;//退款原因
    @BindView(R.id.rtAmountLinearlay)
    LinearLayout rtAmountLinearlay;//退款金额
    @BindView(R.id.rtTipLinearlay)
    LinearLayout rtTipLinearlay;//退款说明
    @BindView(R.id.rtReasonToast)
    LinearLayout rtReasonToast;//退款原因


    @BindView(R.id.rt_type_ex)
    TextView rtTypeEx;//我要换货
    @BindView(R.id.rt_type_rt)
    TextView rtTypeRt;//我要退货
    @BindView(R.id.rt_type_draw)
    TextView rtTypeDraw;//我要退款

    @BindView(R.id.rt_type_ex_im)
    ImageView rtTypeExIm;//我要退款
    @BindView(R.id.rt_type_rt_im)
    ImageView rtTypeRtIm;//我要退款
    @BindView(R.id.rt_type_draw_im)
    ImageView rtTypeDrawIm;//我要退款

    @BindView(R.id.goods_status_0_img)
    ImageView goodsStatusImg0;//未收到货
    @BindView(R.id.goods_status_1_img)
    ImageView goodsStatusImg1;//已收到货

    @BindView(R.id.rt_tip_tip)
    EditText rtTip;//退款说明
    @BindView(R.id.rt_amount_tip)
    EditText rtAmount;//退款金额

    @BindView(R.id.rt_type_ex_rela)
    RelativeLayout rtTypeExRela;//我要换货
    @BindView(R.id.rt_type_rt_rela)
    RelativeLayout rtTypeRtRela;//我要退货
    @BindView(R.id.rt_type_draw_rela)
    RelativeLayout rtTypeDrawRela;//我要退款
    @BindView(R.id.goodsStatusRela0)
    RelativeLayout goodsStatusRela0;//未收到货
    @BindView(R.id.goodsStatusRela1)
    RelativeLayout goodsStatusRela1;//已收到货
    @BindView(R.id.rt_reason)
    TextView rtReason;
    @BindView(R.id.commitApply)
    TextView commitApply;

    @BindView(R.id.imageViewLoader)
    ImageViewUpLoad imageViewLoader;
    @BindView(R.id.iv_img1)
    ImageView iv_img1 ;
    @BindView(R.id.iv_img2)
    ImageView iv_img2 ;
    @BindView(R.id.iv_img3)
    ImageView iv_img3 ;
    @BindView(R.id.iv_clear_img1)
    ImageView iv_clear_img1;
    @BindView(R.id.iv_clear_img2)
    ImageView iv_clear_img2 ;
    @BindView(R.id.iv_clear_img3)
    ImageView iv_clear_img3;
    @BindView(R.id.iv_add_img1)
    ImageView iv_add_img1 ;
    @BindView(R.id.iv_add_img2)
    ImageView iv_add_img2;
    @BindView(R.id.iv_add_img3)
    ImageView iv_add_img3;

    @BindView(R.id.imageLoadRela)
    RelativeLayout imageLoadRela;


    private Integer orderId;
    private Integer goodsId;
    private Integer status;
    private Double detailAmount;

    private Integer rtType=-1;//退款类型
    private Integer goodsStatus=-1;//收货状态
    private Integer fundReason = -1;
    private List<RtListEntity.Rt> rtList;
    private CharSequence[] chars;

    public static final int ACTION_TYPE_ALBUM = 0;//相册
    public static final int ACTION_TYPE_PHOTO = 1;//拍照

    private String theLarge, theThumbnail;
    private File imgFile;

    private List<Bitmap> bitmapsList = new ArrayList<>();//存储bitmap
    private List<File> fileList = new ArrayList<>();//存储文件
    private int index;//当前操作第几张图

    @Override
    public void initView() {
        title.setText(BaseApplication.getIntstance().getResources().getString(R.string.sales_apply));
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        rtTypeExRela.setOnClickListener(this);
        rtTypeRtRela.setOnClickListener(this);
        rtTypeDrawRela.setOnClickListener(this);
        goodsStatusRela0.setOnClickListener(this);
        goodsStatusRela1.setOnClickListener(this);
        rtReasonToast.setOnClickListener(this);
        commitApply.setOnClickListener(this);

        iv_clear_img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index= ImageViewUpLoad.PIC_ONE;
                handleDelPicture(ImageViewUpLoad.PIC_ONE);
            }
        });
        iv_clear_img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_TWO;
                handleDelPicture(ImageViewUpLoad.PIC_TWO);
            }
        });
        iv_clear_img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_THREE;
                handleDelPicture(ImageViewUpLoad.PIC_THREE);
            }
        });
        iv_img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_ONE;
                handleSelectPicture(ImageViewUpLoad.PIC_ONE);
            }
        });
        iv_add_img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_ONE;
                handleSelectPicture(ImageViewUpLoad.PIC_ONE);
            }
        });
        iv_img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_ONE;
                handleSelectPicture(ImageViewUpLoad.PIC_ONE);
            }
        });
        iv_add_img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_TWO;
                handleSelectPicture(ImageViewUpLoad.PIC_TWO);
            }
        });
        iv_img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_ONE;
                handleSelectPicture(ImageViewUpLoad.PIC_ONE);
            }
        });
        iv_add_img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=ImageViewUpLoad.PIC_THREE;
                handleSelectPicture(ImageViewUpLoad.PIC_THREE);
            }
        });
    }

    @Override
    public void initData() {
        orderId = getIntent().getIntExtra("orderId",0);
        goodsId = getIntent().getIntExtra("goodsId",0);
        status = getIntent().getIntExtra("status",0);
        detailAmount = getIntent().getDoubleExtra("amount",0.00);
        if(OrderEnum.PAYED.ordinal()==status){
            rtTypeLinearlay.setVisibility(View.GONE);
            goodsStatusLinearlay.setVisibility(View.GONE);
            rtAmount.setFocusable(false);
            rtType = 0;
            goodsStatus = 0;
            rtAmount.setText(detailAmount+"");
            imageLoadRela.setVisibility(View.GONE);
        }
        requestRtType();
    }

    private void requestRtType() {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);

        final OkUtilCallback okUtilCallback =  new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(getFragmentTag(),response);
                RtListEntity entity = gson.fromJson(response,RtListEntity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                } else{
                    rtList = entity.getList();
                    chars = new CharSequence[rtList.size()];
                    for(int i=0;i<rtList.size();i++){
                        chars[i] = rtList.get(i).getName();
                    }
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.RTLIST, "", okUtilCallback);
    }

    @Override
    public int getContentViewId() {
        return R.layout.after_sale_apply_activity;
    }

    @Override
    protected String getFragmentTag() {
        return AfterSalesActivity.class.getSimpleName();
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==back.getId()){
            finish();
        }else if(view.getId()==rtTypeExRela.getId()){
            rtType=2;
            goodsStatus = 1;
            rtAmountLinearlay.setVisibility(View.GONE);
            goodsStatusLinearlay.setVisibility(View.GONE);
            rtTypeExIm.setVisibility(View.VISIBLE);
            rtTypeDrawIm.setVisibility(View.GONE);
            rtTypeRtIm.setVisibility(View.GONE);
            rtTypeEx.setTextColor(getResources().getColor(R.color.title_color));
            rtTypeDraw.setTextColor(getResources().getColor(R.color.black));
            rtTypeRt.setTextColor(getResources().getColor(R.color.black));
        }else if(view.getId()==rtTypeRtRela.getId()){
            rtType=0;
            goodsStatus =1;
            rtAmountLinearlay.setVisibility(View.VISIBLE);
            goodsStatusLinearlay.setVisibility(View.GONE);
            rtTypeExIm.setVisibility(View.GONE);
            rtTypeDrawIm.setVisibility(View.GONE);
            rtTypeRtIm.setVisibility(View.VISIBLE);
            rtTypeEx.setTextColor(getResources().getColor(R.color.black));
            rtTypeDraw.setTextColor(getResources().getColor(R.color.black));
            rtTypeRt.setTextColor(getResources().getColor(R.color.title_color));
        }else if(view.getId()==rtTypeDrawRela.getId()){
            rtType=3;
            rtAmountLinearlay.setVisibility(View.VISIBLE);
            goodsStatusLinearlay.setVisibility(View.VISIBLE);
            rtTypeExIm.setVisibility(View.GONE);
            rtTypeDrawIm.setVisibility(View.VISIBLE);
            rtTypeRtIm.setVisibility(View.GONE);
            rtTypeEx.setTextColor(getResources().getColor(R.color.black));
            rtTypeDraw.setTextColor(getResources().getColor(R.color.title_color));
            rtTypeRt.setTextColor(getResources().getColor(R.color.black));
        }else if(view.getId()==goodsStatusRela0.getId()){
            goodsStatus=0;
            goodsStatusImg0.setVisibility(View.VISIBLE);
            goodsStatusImg1.setVisibility(View.GONE);
            imageLoadRela.setVisibility(View.GONE);
            rtType=1;
        }else if(view.getId()==goodsStatusRela1.getId()){
            goodsStatus=1;
            goodsStatusImg0.setVisibility(View.GONE);
            goodsStatusImg1.setVisibility(View.VISIBLE);
            imageLoadRela.setVisibility(View.VISIBLE);
        }else if(view.getId()==rtReasonToast.getId()){
           final CommonDialog commonDialog =  DialogHelper.getPinterestDialogCancelable(this);
            commonDialog.setNegativeButton(R.string.cancel, null);
            commonDialog.setTitle(R.string.choose_rt_reason);
            commonDialog.setItemsWithoutChk(chars, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    fundReason = rtList.get(position).getVal();
                    rtReason.setText(rtList.get(position).getName());
                    commonDialog.dismiss();
                }
            });
            commonDialog.show();
        }else if(view.getId()==commitApply.getId()){
            commitRequest();
        }
    }


    /**
     * 提交换货申请
     */
    private void commitRequest() {
        if(rtType<0){
            BaseApplication.showToast(R.string.select_rt_tip);
            return;
        }

        if(goodsStatus<0){
            BaseApplication.showToast(R.string.select_goods_tip);
            return;
        }

        if(fundReason<0){
            BaseApplication.showToast(R.string.select_rt_reason_tip);
            return;
        }

        if(StringUtils.isEmpty(rtAmount.getText().toString())&&rtType!=2){
            BaseApplication.showToast(R.string.select_rt_amount_tip);
            return;
        }

        if(rtType!=2&&Double.parseDouble(rtAmount.getText().toString())>detailAmount){
            BaseApplication.showToast(R.string.rt_amount_error_tip);
            return;
        }

        if(StringUtils.isEmpty(rtTip.getText().toString())){
            BaseApplication.showToast(R.string._rt_reason_tip1);
            return;
        }



        //提交申请
        showWaitDialog(R.string.commit_apply);
        String userId = SPUtils.getStringData(AfterSalesActivity.this, SPUtils.USERID);;
        final OkUtilCallback okUtilCallback = new OkUtilCallback(){
            @Override
            public void onMyResponse(String response, int id) {
                hideWaitDialog();
                TLog.log(getFragmentTag(),response);
                Entity entity = gson.fromJson(response,Entity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.showToast(R.string.commit_apply_success);
                    Intent intent = new Intent(AfterSalesActivity.this,OrderListActiviy.class);
                    startActivity(intent);
                }
            }
        };
        HashMap<String,List<File>> map = new HashMap<>();
        map.put("rtImgs",fileList);

        String url = "userId=" + userId+"&orderId="+orderId+"&goodsIds="+goodsId+"&content="+rtTip.getText().toString()
                +"&reasonId="+fundReason +"&type="+rtType+"&status="+goodsStatus;

        if(rtType!=2){
            url += "&amount="+rtAmount.getText().toString();
        }

        OKUtilAPI.file(OKUtilAPI.RT, url , okUtilCallback,map);
    }


    /**
     * 删除照片
     * @param index
     */
    private void handleDelPicture(int index) {
        if(index==ImageViewUpLoad.PIC_ONE){//删除第一张
            if(bitmapsList.size()==1){
                bitmapsList.remove(0);
                fileList.remove(0);
                iv_add_img1.setVisibility(View.VISIBLE);
                iv_add_img2.setVisibility(View.VISIBLE);
                iv_add_img3.setVisibility(View.VISIBLE);
            }else if(bitmapsList.size()==2){
                bitmapsList.remove(0);
                fileList.remove(0);
                iv_img1.setImageBitmap(bitmapsList.get(0));
                iv_add_img1.setVisibility(View.GONE);
                iv_add_img2.setVisibility(View.VISIBLE);
                iv_add_img3.setVisibility(View.VISIBLE);
            }else if(bitmapsList.size()==3){
                bitmapsList.remove(0);
                fileList.remove(0);
                iv_img1.setImageBitmap(bitmapsList.get(0));
                iv_img2.setImageBitmap(bitmapsList.get(1));
                iv_add_img1.setVisibility(View.GONE);
                iv_add_img2.setVisibility(View.GONE);
                iv_add_img3.setVisibility(View.VISIBLE);
            }
        }else if(index==ImageViewUpLoad.PIC_TWO){//删除第二张
            if(bitmapsList.size()==2){
                bitmapsList.remove(1);
                fileList.remove(1);
                iv_img1.setImageBitmap(bitmapsList.get(0));
                iv_add_img1.setVisibility(View.GONE);
                iv_add_img2.setVisibility(View.VISIBLE);
                iv_add_img3.setVisibility(View.VISIBLE);
            }else if(bitmapsList.size()==3){
                bitmapsList.remove(1);
                fileList.remove(0);
                iv_img1.setImageBitmap(bitmapsList.get(0));
                iv_img2.setImageBitmap(bitmapsList.get(1));
                iv_add_img1.setVisibility(View.GONE);
                iv_add_img2.setVisibility(View.GONE);
                iv_add_img3.setVisibility(View.VISIBLE);
            }
        }else if(index==ImageViewUpLoad.PIC_TWO){//删除第三张
            bitmapsList.remove(2);
            fileList.remove(0);
            iv_img1.setImageBitmap(bitmapsList.get(0));
            iv_img2.setImageBitmap(bitmapsList.get(1));
            iv_add_img1.setVisibility(View.GONE);
            iv_add_img2.setVisibility(View.GONE);
            iv_add_img3.setVisibility(View.VISIBLE);
        }
    }


    private void handleSelectPicture( int index) {
        final CommonDialog dialog = DialogHelper
                .getPinterestDialogCancelable(this);
        dialog.setTitle(R.string.choose_picture);
        dialog.setNegativeButton(R.string.cancel, null);
        dialog.setItemsWithoutChk(
                BaseApplication.getIntstance().getResources().getStringArray(R.array.choose_picture),
                new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        dialog.dismiss();
                        goToSelectPicture(position);
                    }
                });
        dialog.show();
    }

    private void goToSelectPicture(int position) {
        theLarge = "";
        theThumbnail = "";
        switch (position) {
            case ACTION_TYPE_ALBUM:
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, BaseApplication.getIntstance().getResources().getString(R.string.choose_picture)),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, BaseApplication.getIntstance().getResources().getString(R.string.choose_picture)),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
                }
                break;
            case ACTION_TYPE_PHOTO:
                // 判断是否挂载了SD卡
                String savePath = "";
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    savePath = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/somosteld/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }
                }

                // 没有挂载SD卡，无法保存文件
                if (StringUtils.isEmpty(savePath)) {
                    BaseApplication.showToastShort("无法保存照片，请检查SD卡是否挂载");
                    return;
                }

                String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                        .format(new Date());
                String fileName = "ddapp_" + timeStamp + ".jpg";// 照片命名
                File out = new File(savePath, fileName);
                Uri uri = Uri.fromFile(out);

                theLarge = savePath + fileName;// 该照片的绝对路径

                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent,
                        ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode,
                                 final Intent imageReturnIntent) {
        if (resultCode != Activity.RESULT_OK)
            return;
        new Thread() {
            private String selectedImagePath;

            @Override
            public void run() {
                Bitmap bitmap = null;

                if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) {
                    if (imageReturnIntent == null)
                        return;
                    Uri selectedImageUri = imageReturnIntent.getData();
                    if (selectedImageUri != null) {
                        selectedImagePath = ImageUtils.getImagePath(
                                selectedImageUri, AfterSalesActivity.this);
                    }

                    if (selectedImagePath != null) {
                        theLarge = selectedImagePath;
                    } else {
                        bitmap = ImageUtils.loadPicasaImageFromGalley(
                                selectedImageUri, AfterSalesActivity.this);
                    }

                    if (MethodsCompat
                            .isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                        String imaName = FileUtil.getFileName(theLarge);
                        if (imaName != null)
                            bitmap = ImageUtils.loadImgThumbnail(AfterSalesActivity.this,
                                    imaName,
                                    MediaStore.Images.Thumbnails.MICRO_KIND);
                    }
                    if (bitmap == null && !StringUtils.isEmpty(theLarge))
                        bitmap = ImageUtils
                                .loadImgThumbnail(theLarge, 100, 100);
                } else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA) {
                    // 拍摄图片
                    if (bitmap == null && !StringUtils.isEmpty(theLarge)) {
                        bitmap = ImageUtils
                                .loadImgThumbnail(theLarge, 100, 100);
                    }
                }

                if (bitmap != null) {// 存放照片的文件夹
                    String savePath = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/SOMOSTELD/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtil.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 判断是否已存在缩略图
                    if (largeFileName.startsWith("thumb_")
                            && new File(largeFilePath).exists()) {
                        theThumbnail = largeFilePath;
                        imgFile = new File(theThumbnail);
                    } else {
                        // 生成上传的800宽度图片
                        String thumbFileName = "thumb_" + largeFileName;
                        theThumbnail = savePath + thumbFileName;
                        if (new File(theThumbnail).exists()) {
                            imgFile = new File(theThumbnail);
                        } else {
                            try {
                                // 压缩上传的图片
                                ImageUtils.createImageThumbnail(AfterSalesActivity.this,
                                        theLarge, theThumbnail, 800, 80);
                                imgFile = new File(theThumbnail);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    private Handler handler = new Handler(){
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1 && msg.obj != null) {
                Bitmap bitmap = (Bitmap)msg.obj;
                if(index==ImageViewUpLoad.PIC_ONE){//增加第一张
                    if(bitmapsList.size()>=1){
                        bitmapsList.remove(0);
                        fileList.remove(0);
                    }
                    bitmapsList.add(0,bitmap);
                    fileList.add(0,imgFile);
                    iv_img1.setImageBitmap(bitmap);
                    iv_add_img1.setVisibility(View.GONE);
                }else if(index==ImageViewUpLoad.PIC_TWO){//增加第二张
                    if(bitmapsList.size()==0){
                        bitmapsList.add(bitmap);
                        fileList.add(imgFile);
                        iv_img1.setImageBitmap(bitmapsList.get(0));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.VISIBLE);
                        iv_add_img3.setVisibility(View.VISIBLE);
                    } else if(bitmapsList.size()==1){
                        bitmapsList.add(bitmap);
                        fileList.add(imgFile);
                        iv_img2.setImageBitmap(bitmapsList.get(1));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.VISIBLE);
                    }else if(bitmapsList.size()==2){
                        bitmapsList.remove(1);
                        bitmapsList.add(1,bitmap);
                        fileList.remove(1);
                        fileList.add(1,imgFile);
                        iv_img2.setImageBitmap(bitmapsList.get(1));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.VISIBLE);
                    }else if(bitmapsList.size()==3){
                        bitmapsList.remove(1);
                        bitmapsList.add(1,bitmap);
                        fileList.remove(1);
                        fileList.add(1,imgFile);
                        iv_img1.setImageBitmap(bitmapsList.get(1));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.GONE);
                    }
                }else if(index==ImageViewUpLoad.PIC_THREE){//增加第三张
                    if(bitmapsList.size()==0){
                        bitmapsList.add(bitmap);
                        fileList.add(imgFile);
                        iv_img1.setImageBitmap(bitmapsList.get(0));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.VISIBLE);
                        iv_add_img3.setVisibility(View.VISIBLE);
                    } else if(bitmapsList.size()==1){
                        bitmapsList.add(bitmap);
                        fileList.add(imgFile);
                        iv_img2.setImageBitmap(bitmapsList.get(1));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.VISIBLE);
                    }else if(bitmapsList.size()==2){
                        bitmapsList.add(bitmap);
                        fileList.add(imgFile);
                        iv_img3.setImageBitmap(bitmapsList.get(2));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.GONE);
                    }else if(bitmapsList.size()==3){
                        bitmapsList.remove(2);
                        bitmapsList.add(2,bitmap);
                        fileList.remove(2);
                        fileList.add(2,imgFile);
                        iv_img3.setImageBitmap(bitmapsList.get(2));
                        iv_add_img1.setVisibility(View.GONE);
                        iv_add_img2.setVisibility(View.GONE);
                        iv_add_img3.setVisibility(View.GONE);
                    }
                }
            }
        }
    };
}
